package com.gillion.grule.client.core.variable;

import com.gillion.grule.client.exception.ExecutorException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.collections.MapUtils;
import org.mvel2.MVEL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class BaseVariable implements Serializable {
    private static final Logger log = LoggerFactory.getLogger(BaseVariable.class);

    protected String name;
    protected Map<String, Object> variables = new HashMap<>();


    private boolean isInit = true;

    public Object getVariable(String name) {
        return this.variables.get(name);
    }




    public void init() {
        if (this.isInit) {
            Set<String> keys = this.variables.keySet();
            for (String key : keys) {
                try {
                    Object obj;
                    if (!MapUtils.getObject(this.variables, key).getClass().isPrimitive() && !(MapUtils.getObject(this.variables, key) instanceof String)) {
                        obj = MapUtils.getObject(this.variables, key);
                    } else {
                        obj = MVEL.eval(MapUtils.getString(this.variables, key));
                    }
                    this.variables.put(key, obj);
                } catch (Exception e) {
                    throw new ExecutorException("变量:" + key + " 初始化异常，请检查！", e);
                }
            }
            this.isInit = false;
        }
    }


    public String toString() {
        return "BaseVariable{name='" + this.name + '\'' + ", variables=" + this.variables + '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BaseVariable that = (BaseVariable) o;
        return isInit == that.isInit &&
                Objects.equals(name, that.name) &&
                Objects.equals(variables, that.variables);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, variables, isInit);
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<String, Object> getVariables() {
        return this.variables;
    }

    public void setVariables(Map<String, Object> variables) {
        this.variables = variables;
    }

    public void setVariables(String key, Object obj) {
        this.variables.put(key, obj);
    }
}


